using System;
using System.ServiceModel;
using Microsoft.Practices.Unity;
using Sern.Abstracts.Tracker.DataContracts;
using Sern.Common;

namespace Sern.ServiceImplementation
{
    public class ListenerFactory : IListenerFactory
    {
        public Listener Create(Uri baseAddress, Uri endpointAddress, ClientType clientType, object instance)
        {
            var contractType = ComponentLocator.Unity.Resolve<IClientTypeToEnumMapper>()[clientType];
            var bindingScheme = ComponentLocator.Unity.Resolve<IBindingFactory>()[clientType]();

            var listener = new ServiceHost(
                instance, baseAddress);

            listener.AddServiceEndpoint(
                contractType,
                bindingScheme.Binding,
                endpointAddress
                );

            listener.EnableMex();
            listener.ConfigureAsSingleton();

            return new Listener
                {
                    Open = listener.Open,
                    Close = listener.Close,
                    Dispose = (listener as IDisposable).Dispose
                };
        }
    }
}